package com.scau.jansing.thread.first;

import java.util.ArrayList;
import java.util.concurrent.*;

/**
 * Created by jansing on 2015/12/1.
 */
public class CallableDemo {
    public static void main(String[] args){
        ExecutorService exec = Executors.newCachedThreadPool();
        ArrayList<Future<String>> results = new ArrayList<>();
        for(int i=0; i<100; i++){
            results.add(exec.submit(new TaskWithResult(i)));
        }
        System.out.println("outer");

        for(int i=0; i<100; i++){
            //如果某个线程未完成并返回结果，则阻塞
            try {
                //使用isDone来判断线程是否结束并返回结果。
//                results.get(i).isDone();
                System.out.println(results.get(i).get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }finally{
                exec.shutdown();
            }
        }
        System.out.println("outer2");
    }




}



class TaskWithResult implements Callable<String> {
    private int id;

    public TaskWithResult(int id){
        this.id = id;
    }

    @Override
    public String call() throws Exception {
        for(int i=0; i<5; i++){
            System.out.println("inner " + id);
//            Thread.yield();
            Thread.sleep(100);
        }
        return "result of TaskWithResult " + id;
    }
}